package com.ptswitch.material.pages.security;

import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.tapestry5.model.TreeModel;
import org.hxzon.tapestry5.model.ValueLabel;

import com.ptswitch.material.model.security.Permission;
import com.ptswitch.material.model.security.Role;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.PermissionService;
import com.ptswitch.material.service.RoleService;
import com.ptswitch.material.util.HlogConstants;
import com.ptswitch.material.util.ValueLabelUtil;
import com.ptswitch.material.util.security.PermissionTreeUtil;
import com.ptswitch.material.util.security.PermissionUtil;

public class CreateRole extends PageBase {

    @Inject
    private RoleService roleSer;
    @Inject
    private PermissionService permissionSer;
    @InjectPage
    private ListRole listRole;
    //
    @Property
    private Role role;
    @Property
    private List<Permission> permissions;
    @Property
    private TreeModel<Permission> permissionTreeModel = PermissionTreeUtil.permissionTreeModel;
    @Property
    private ValueLabel<Permission> permissionLabel;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init() {
        checkPermitted(PermissionUtil.RoleCreate);
        role = new Role();
        permissions = permissionSer.findAll();
        permissionLabel = ValueLabelUtil.permissionLabel;
        return null;
    }

    @OnEvent(component = "add")
    Object add() {
        checkPermitted(PermissionUtil.RoleCreate);
        roleSer.save(role);
        hlog(HlogConstants.addRole, role);
        return listRole;
    }
}
